﻿package 华为练习2;

import java.util.*;

/**
 * Created by hest0 on 2017/7/12.
 */

class Student {
    String name;
    Integer score;
    Integer order;

    Student(String name, Integer score, Integer order) {
        this.name = name;
        this.score = score;
        this.order = order;
    }
}

public class 成绩排序Map排序 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int n = Integer.parseInt(sc.nextLine());
            int flag = Integer.parseInt(sc.nextLine());

            ArrayList<Student> list = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                String[] a = sc.nextLine().trim().split("\\s+");
                String name = a[0];
                int score = Integer.parseInt(a[1]);
                int order = i + 1;
                Student student = new Student(name, score, order);
                list.add(student);
            }

            if (flag == 0)
                sortDown(list);
            else
                sortUp(list);


        }
        sc.close();
    }

    private static void sortUp(ArrayList<Student> list) {
        Collections.sort(list, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                if (o1.score.intValue() != o2.score.intValue())
                    return o1.score < o2.score ? -1 : 1;
                return o1.order < o2.order ? -1 : 1;
            }
        });
        for (Student x : list) {
            System.out.println(x.name + " " + x.score);
        }
    }

    private static void sortDown(ArrayList<Student> list) {
        Collections.sort(list, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                if (o1.score.intValue() != o2.score.intValue())
                    return o1.score < o2.score ? 1 : -1;
                return o1.order < o2.order ? -1 : 1;
            }
        });
        for (Student x : list) {
            System.out.println(x.name + " " + x.score);
        }
    }


}
